package org.komarichin.tags;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;

/**
 * <p>
 * &nbsp;
 * </p>
 * User: Michael Komarichin
 * Date: Feb 15, 2010
 * Time: 9:34:54 PM
 */
public class SourceTag extends TagSupport {
    private static final long serialVersionUID = -5279309813316327882L;
    private static final Logger log = LoggerFactory.getLogger(SourceTag.class);

    private String link;
    private String alt;
    private String title;
    private String target;

    @Override
    public int doStartTag() throws JspException {

        if (StringUtils.isNotEmpty(link)) {
            StringBuilder builder = new StringBuilder("");
            if (link.startsWith("http")) {
                String showLink = link;
                if (link.length() > 35) showLink = link.substring(0, 35) + "...";
                builder.append("<a href=\"").append(link).append("\" alt=\"").append(StringUtils.defaultIfEmpty(alt, StringUtils.EMPTY)).
                        append("\" title=\"").append(StringUtils.defaultIfEmpty(title, StringUtils.EMPTY)).append("\"").
                        append(" target=\"").append(StringUtils.defaultIfEmpty(target, "_blank")).append("\">").append(showLink).append("</a>");
                try {
                    pageContext.getOut().write(builder.toString());
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return SKIP_BODY;
    }

    @Override
    public void release() {
        super.release();
        alt = title = target = link = null;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }

    public String getAlt() {
        return alt;
    }

    public void setAlt(String alt) {
        this.alt = alt;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getTarget() {
        return target;
    }

    public void setTarget(String target) {
        this.target = target;
    }
}
